package com.neusoft.controller;


import com.neusoft.common.Result;
import com.neusoft.pojo.Dept;
import com.neusoft.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

//提供 restFul 服务
@RestController
@RequestMapping("/dept")
public class DeptController {

    @Autowired
    DeptService deptService;

    //获取一些配置信息
    @Autowired
    private DiscoveryClient client;

    /*新增的部门数据*/
    @PostMapping
    public boolean addDept(@RequestBody Dept dept){

        return deptService.addDept(dept);
    }

    /*查询部门根据ID*/
    @GetMapping("/{id}")
    public Result<?> queryById(@PathVariable("id") long id){
        Dept dept = deptService.queryById(id);
        Integer i = Optional.ofNullable(dept).map(Dept::getId).orElse(null);
        if (i.equals(null)) {
            return Result.error("300", "没有查询到数据");
        }
        return  Result.success(dept);
    }

    /*查询所有，可以带查询条件，查询条件以json实体形式推送*/
    @GetMapping
    public List<Dept> queryAll(@RequestBody Dept dept){
        return deptService.queryAll(dept);
    }

    /*更新部门根据根据ID*/
    @PutMapping
    public Result<?> updateDeptById(@RequestBody Dept dept){
        int s = deptService.updateDeptById(dept);
        if (1 == s) {
            return  Result.success("更新成功");
        }
        return Result.error("500","更新部门失败");
    }


    /*获取注册进来微服务的信息*/
    @RequestMapping("/discovery")
    public Object discovery(){
        // 获取微服务列表的清单
        List<String> services = client.getServices();
        System.out.println("discovery=======>>>>:"+services);

        //得到一个具体的微服务信息
        List<ServiceInstance> instances = client.getInstances("SPRINGCLUDE-PROVIDER-DEPT");

        for (ServiceInstance instance : instances) {
            System.out.println(instance.getHost()+"\n"+
                    instance.getPort()+"\n"+
                    instance.getUri()+"\n"+
                    instance.getServiceId());
        }
        return this.client;

    }
}
